package com.sxbbc.seller.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.Address;
import com.sxbbc.common.core.entity.jz.BExpConfig;
import com.sxbbc.common.core.entity.jz.BExpDetail;
import com.sxbbc.common.core.entity.jz.BRefundAddr;
import com.sxbbc.common.core.enums.ValuationTypeEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.seller.common.MappingUtils;
import com.sxbbc.seller.service.BusinessBaseService;
import com.sxbbc.seller.service.BusinessService;
import com.sxbbc.common.core.dto.jz.BExpVo;
import com.sxbbc.seller.util.BusinessSession;
import com.sxbbc.seller.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 物流管理相关 控制层
 *
 * @author leehao
 * @date 2019-05-28 19:49
 */
@SuppressWarnings("all")
@Controller
public class ExpController {

    @Autowired
    private IBRefundAddrService bRefundAddrService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private IBExpConfigService bExpConfigService;
    @Autowired
    private IBExpDetailService bExpDetailService;
    @Autowired
    private BusinessBaseService businessBaseService;
    @Autowired
    private IProcMainService procMainService;

    /**
     * 退货地址列表
     * @param request 获取bid
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_REFUND_ADDR_LIST)
    public ModelAndView showRefundAddrList(HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        QueryWrapper<BRefundAddr> wrapper = new QueryWrapper<>();
        wrapper.eq("bid", bid);
        List<BRefundAddr> list = bRefundAddrService.list(wrapper);
        for (BRefundAddr addr : list) {
            String addrName = businessService.getAddrName(addr.getProId(), addr.getCityId(), addr.getAreaId());
            addr.setAddressDetails(addrName + " " + addr.getAddressDetails());
        }
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_REFUND_ADDR_LIST);
        view.addObject("list", list);
        return view;
    }

    /**
     * 新增编辑退货地址
     * @param id /
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_EDIT_REFUND_ADDR)
    public ModelAndView showEditRefundAddr(Integer id) {
        BRefundAddr addr = bRefundAddrService.getById(id);
        // 地址
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        // 省列表
        List<Address> proList = addressService.queryAddressByParentId(address);
        // 市列表
        List<Address> cityList = new ArrayList<>();
        // 区列表
        List<Address> areaList = new ArrayList<>();
        if (id != null && addr.getProId() != null) {
            address.setPid(addr.getProId());
            cityList = addressService.queryAddressByParentId(address);
        }
        if (id != null && addr.getCityId() != null) {
            address.setPid(addr.getCityId());
            areaList = addressService.queryAddressByParentId(address);
        }
        List<Address> addressList = addressService.queryAddressByParentId(address);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EDIT_REFUND_ADDR);
        view.addObject("addr", addr);
        view.addObject("proList", proList);
        view.addObject("cityList", cityList);
        view.addObject("areaList", areaList);
        return view;
    }

    /**
     * 新增编辑退货地址
     * @param request
     * @param refundAddr
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = MappingUtils.EDIT_REFUND_ADDR)
    @ResponseBody
    @SystemLog(methods = "新增编辑商家退货地址", module = "物流管理")
    public RestResponse editRefundAddr(HttpServletRequest request, BRefundAddr refundAddr) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("获取商家信息失败，请重新登录");
        }
        if (refundAddr.getProId() == null ||
                refundAddr.getCityId() == null ||
                refundAddr.getAreaId() == null) {
            return GetRest.getFail("请选择退货地址");
        }
        if (StringUtils.isBlank(refundAddr.getAddressDetails())) {
            return GetRest.getFail("请输入退货地址详情");
        }
        if (StringUtils.isBlank(refundAddr.getRevceiver())) {
            return GetRest.getFail("请输入退货收货人");
        }
        if (StringUtils.isBlank(refundAddr.getPhone())) {
            return GetRest.getFail("请输入退货联系电话");
        }
        RpxUtils rpxUtil = RpxUtils.getInstance();
        if (!StringUtils.equals(rpxUtil.validPhone(refundAddr.getPhone()),"")) {
            return GetRest.getFail(rpxUtil.validPhone(refundAddr.getPhone()));
        }
        refundAddr.setBid(bid);
        boolean save = bRefundAddrService.saveOrUpdate(refundAddr);
        if (!save) {
            throw new ThrowJsonException("保存商家退货地址失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 删除退货地址
     * @param id /
     * @author leehao
     * @return boolean
     */
    @RequestMapping(value = MappingUtils.DELETE_REFUND_ADDR)
    @ResponseBody
    @SystemLog(methods = "删除商家退货地址",module = "物流管理")
    public boolean deleteRefundAddr(Integer id){
        return bRefundAddrService.removeById(id);
    }

    /**
     * 运费模板列表页
     * @param request
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_EXP_MODEL)
    public ModelAndView showExpModel(HttpServletRequest request){
        Integer bid = BusinessSession.getBid(request);
        List<BExpConfig> expList = bExpConfigService.queryBusinessExpList(bid);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EXP_MODEL);
        view.addObject("expList",expList);
        return view;
    }

    /**
     * 新增运费模板
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_ADD_EXP_MODEL)
    public ModelAndView showAddExpModel(){
        //省份
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> proList = addressService.queryAddressByParentId(address);
        List<ValuationTypeEnums> valuationList = ValuationTypeEnums.queryList();
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ADD_EXP_MODEL);
        view.addObject("proList",proList);
        view.addObject("valuationList",valuationList);
        return view;
    }

    /**
     * 编辑运费模板
     * @param id 模板ID
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_EDIT_EXP_MODEL)
    public ModelAndView showEditExpModel(Integer id){
        //省份
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> proList = addressService.queryAddressByParentId(address);
        BExpConfig expConfig = bExpConfigService.getById(id);
        QueryWrapper<BExpDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("expid",id);
        List<BExpDetail> bExpDetails = bExpDetailService.list(wrapper);
        BExpDetail bExpDetail = bExpDetails.get(0);
        List<BExpDetail> detailList = bExpDetails.subList(1, bExpDetails.size());
        if (!CollectionUtils.isEmpty(detailList)) {
            for (BExpDetail expDetail : detailList) {
                expDetail.setAddressEdit(businessBaseService.handleEditAddressShow(expDetail.getProid(),expDetail.getCityid()));
            }
        }
        List<ValuationTypeEnums> valuationList = ValuationTypeEnums.queryList();
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EDIT_EXP_MODEL);
        view.addObject("proList",proList);
        view.addObject("valuationList",valuationList);
        view.addObject("expConfig",expConfig);
        view.addObject("detailList",detailList);
        view.addObject("bExpDetail",bExpDetail);
        return view;
    }

    /**
     * 运费模板 选择地址
     * @param modelId 模板ID
     * @param addr 省市地址字符串
     * @author leehao
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_EXP_ADDRESS)
    public ModelAndView showExpAddress(String modelId, String addr){
        //地址集合对象
        //地址字符串不为空时进行处理后，页面选中状态；为空传入完整地址对象
        List<Address> addrList = new ArrayList<>();
        if (StringUtils.isNotBlank(addr)) {
            addrList = businessBaseService.handleExpAddress(addr);
        }else{
            addrList = addressService.queryAllAddress();
        }
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EXP_ADDRESS);
        view.addObject("modelId",modelId);
        view.addObject("list",addrList);
        return view;
    }

    /**
     * 新增运费模板
     * @param request
     * @param bExpVo
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = MappingUtils.ADD_EXP_MODEL)
    @ResponseBody
    @SystemLog(methods = "新增/编辑商家运费模板",module = "物流管理")
    public RestResponse addExpModel(HttpServletRequest request,
                                     BExpVo bExpVo){
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        if (StringUtils.isBlank(bExpVo.getName())) {
            return GetRest.getFail("请输入模板名称");
        }
        if (bExpVo.getValuationType() == null) {
            return GetRest.getFail("请选择计价方式");
        }
        if (bExpVo.getValuationType() == null) {
            return GetRest.getFail("请选择计价方式");
        }
        if (bExpVo.getMoney() == null || bExpVo.getVals() == null) {
            return GetRest.getFail("请输入包邮规则");
        }
        if (bExpVo.getBeginNum() == null || bExpVo.getBeginNum().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getBeginMoney() == null || bExpVo.getBeginMoney().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddNum() == null || bExpVo.getAddNum().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddMoney() == null || bExpVo.getAddMoney().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddrDetail() == null) {
            return GetRest.getFail("请选择地址");
        }
        bExpVo.setBid(bid);
        //处理地址字符串
        BExpVo expVo = businessBaseService.handleAddAddress(bExpVo);
        return bExpConfigService.addExpModel(expVo);
    }

    /**
     * 编辑运费模板
     * @param request 获取bid
     * @param bExpVo 运费模板vo对象
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = MappingUtils.EDIT_EXP_MODEL)
    @ResponseBody
    public RestResponse editExpModel(HttpServletRequest request,BExpVo bExpVo){
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        if (bExpVo.getId() == null) {
            return GetRest.getFail("请选择模板");
        }
        if (StringUtils.isBlank(bExpVo.getName())) {
            return GetRest.getFail("请输入模板名称");
        }
        if (bExpVo.getValuationType() == null) {
            return GetRest.getFail("请选择计价方式");
        }
        if (bExpVo.getMoney() == null || bExpVo.getVals() == null) {
            return GetRest.getFail("请输入包邮规则");
        }
        if (bExpVo.getBeginNum() == null || bExpVo.getBeginNum().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getBeginMoney() == null || bExpVo.getBeginMoney().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddNum() == null || bExpVo.getAddNum().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddMoney() == null || bExpVo.getAddMoney().length < 1) {
            return GetRest.getFail("请填写完整的模板信息");
        }
        if (bExpVo.getAddrDetail() == null) {
            return GetRest.getFail("请选择地址");
        }
        bExpVo.setBid(bid);
        //处理地址字符串
        BExpVo expVo = businessBaseService.handleAddAddress(bExpVo);
        return bExpConfigService.editExpModel(bExpVo);
    }

    /**
     * 删除商家运费模板
     * @param id 模板id
     * @author leehao
     * @return boolean
     */
    @RequestMapping(value = MappingUtils.DELETE_EXP_MODEL)
    @ResponseBody
    @SystemLog(methods = "删除商家运费模板",module = "物流管理")
    public boolean deleteExpModel(Integer id){
        boolean delete = false;
        QueryWrapper<BExpDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("expid",id);
        delete = bExpConfigService.removeById(id);
        delete = bExpDetailService.remove(wrapper);
        if (!delete) {
            throw new ThrowJsonException("删除商家运费模板失败");
        }
        //删除运费模板，对相应的商品下架
        delete = procMainService.handleProductStatusWithDeleteExp(id);
        if (!delete) {
            throw new ThrowJsonException("删除商家运费模板处理商品失败");
        }
        return delete;
    }

    /**
     * 删除运费模板详情单条
     * @param id 详情ID
     * @author leehao
     * @return com.function.common.RestResponse
     */
    @RequestMapping(value = MappingUtils.HANDLE_DELETE_EXP_DETAIL)
    @ResponseBody
    public RestResponse deleteExpDetail(Integer id){
        boolean delete = bExpDetailService.removeById(id);
        if (!delete) {
            throw new ThrowJsonException("删除运费详情失败");
        }
        return  GetRest.getSuccess("删除成功");
    }
}
